package com.dji.common.utils;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dji.common.api.DateAPI;

public class TimeUtil {
	private final static Logger log = LoggerFactory.getLogger(TimeUtil.class);

	public static String getDefaultStyleCurrentTimeStr() {
		return getCurrentTimeByStyle("yyyy-MM-dd hh-mm-ss");
	}

	public static Date getDateByStringStyle(String date) throws ParseException {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
		return format.parse(date);
	}

	public static String getCurrentTimeByStyle(String style) {
		DateFormat format = new SimpleDateFormat(style == null ? "yyyy-MM-dd" : style);
		return format.format(new Date());
	}

	public static String getDateTimeByStyle(Date date, String style) {
		DateFormat format = new SimpleDateFormat(style == null ? "yyyy-MM-dd hh-mm-ss" : style);
		return format.format(date);
	}

	/**
	 * 设置当前主机时间
	 * 
	 * @param serviceDate
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void synchronousServiceDate(Date serviceDate) throws Exception {
		if (null == serviceDate) {
			serviceDate = DateAPI.getInternateDateTime();
		}
		String osName = System.getProperty("os.name").toLowerCase();
		if (osName.equals("linux")) {

		} else if (osName.startsWith("windows")) {
			String serverDate = getDateTimeByStyle(serviceDate, "yyyy-MM-dd");
			Process exec = Runtime.getRuntime().exec("cmd /c date " + serverDate);
			if (exec.waitFor() == 0) {
				log.debug("设置系统日期成功：" + serverDate);
			} else {
				log.debug("设置系统日期失败：" + serverDate);
			}
			String serverTime = getDateTimeByStyle(serviceDate, "hh:mm:ss");
			exec = Runtime.getRuntime().exec("cmd /c time " + serverTime);
			if (exec.waitFor() == 0) {
				log.debug("设置系统时间成功：" + serverTime);
			} else {
				log.debug("设置系统时间失败：" + serverTime);
			}
		} else if (osName.startsWith("mac os x")) {

		} else {
			throw new RuntimeException("不支持的操作系统: " + osName);
		}
	}

}
